﻿namespace EFS.RC.CCC.Registrars
{
	abstract class Registrar<RecordType>
	{
		// registrar instance
		private static Registrar<RecordType> instance;

		// lock
		private static object asyncAccess = new object(); 

		// elements
		private System.Collections.Generic.Dictionary<System.String, RecordType> records = new System.Collections.Generic.Dictionary<System.String, RecordType>();

		/// <summary>
		/// Constructor init static instance
		/// </summary>
		private Registrar()
		{
			// lock	
			lock (asyncAccess)
			{
				// check 1 instance
				EFS.Common.Verify.Condition(null == instance, "null == instance");

				// set
				instance = this;
			}
		}

		/// <summary>
		/// Register record
		/// </summary>
		/// <param name="t"></param>
		public void Register(RecordType record)
		{
			// check
			EFS.Common.Verify.Reference(record, "record");

			// lock
			lock (asyncAccess)
			{ 
				// check key not exists
				if (records.ContainsKey(record.Identification))
				{
					throw new System.InvalidOperationException(System.String.Format("Record: {0} already in Registrar", record.Identification));
				}

				// add
				records.Add(record.Identification, record);
			}
		}

		/// <summary>
		/// Find entry in registrar
		/// </summary>
		/// <param name="identification"></param>
		/// <returns></returns>
		public RecordType Find(System.String identification)
		{
			// lock
			lock (asyncAccess)
			{
				// check key not exists
				if (!records.ContainsKey(record.Identification))
				{
					return default(RecordType);
				}

				// add
				return records[record.Identification];
			}			
		}
	}
}
